package com.hellohoper.script.config.api.app.service;

import com.hellohoper.script.config.admin.app.dao.pojo.ScriptConfig;
import com.hellohoper.script.config.api.app.dao.ScriptConfigMapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 配置查询服务
 * Created by hk on 17/8/19.
 */
@Service
public class ScriptConfigService {

    @Autowired
    private RedisTemplate<String, ScriptConfig> redisTemplate;

    @Autowired
    private ScriptConfigMapper scriptConfigMapper;

    /**
     * 脚本查询
     *
     * @param appName    appName
     * @param scriptName scriptName
     * @return 脚本
     */
    public ScriptConfig selectScriptConfig(String appName, String scriptName) {

        // 查询缓存
        ScriptConfig scriptConfigRedis = (ScriptConfig) redisTemplate.opsForHash().get(appName, scriptName);
        if (scriptConfigRedis != null) {
            return scriptConfigRedis;
        }

        // 查询数据库
        ScriptConfig scriptConfig = new ScriptConfig();
        scriptConfig.setAppName(appName);
        scriptConfig.setScriptName(scriptName);
        List<ScriptConfig> scriptConfigs = scriptConfigMapper.selectScriptConfigPageList(scriptConfig);
        if (CollectionUtils.isNotEmpty(scriptConfigs)) {
            return scriptConfigs.get(0);
        }
        return null;
    }

    /**
     * 脚本列表查询
     *
     * @param appName appName
     * @return 脚本列表
     */
    public List<ScriptConfig> selectScriptConfigList(String appName) {

        // 查询缓存
        HashOperations<String, ScriptConfig, ScriptConfig> hashOperations = redisTemplate.opsForHash();
        List<ScriptConfig> values = hashOperations.values(appName);
        if (CollectionUtils.isNotEmpty(values)) {
            return values;
        }

        // 查询数据库
        ScriptConfig scriptConfig = new ScriptConfig();
        scriptConfig.setAppName(appName);
        List<ScriptConfig> scriptConfigs = scriptConfigMapper.selectScriptConfigPageList(scriptConfig);
        return scriptConfigs;
    }
}
